package com.itheima.heima.info.manager.system.dao;

import com.itheima.heima.info.manager.system.domain.Student;

import java.util.ArrayList;

/*
学生操作数据类
学生的增删改查
写在这个类中
使用集合优化代码
 */
public class OtherStudentDao implements BaseStudentDao {

    private static ArrayList<Student> stus = new ArrayList<>();

    static {
        Student cai = new Student("0001", "蔡徐坤", 25, "1996");
        Student lu = new Student("0002", "鹿晗", 30, "1996");
        Student huang = new Student("0003", "黄子韬", 28, "1996");
        Student wu = new Student("0004", "吴亦凡", 28, "1996");
        stus.add(cai);
        stus.add(lu);
        stus.add(huang);
        stus.add(wu);

    }
    @Override
    public boolean addStudent(Student student) {
       stus.add(student);
       return true;
    }

    //查看所有的学生
    @Override
    public Student[] findAll() {
        //创建新的数组 将集合中的数据添加到数组中
        Student[] students = new Student[stus.size()];
        for (int i = 0; i < stus.size(); i++) {
            //stus.get(i) i students[i]
            students[i] =stus.get(i);
        }
        return students;
    }

    public void deleteStudent(String sid) {
        int index = getIndex(sid);
        //把地址值替换为null
       stus.remove(index);


    }

    //根据学号找索引
    /*
    根据条件查询 学号 索引
     */
    public int getIndex(String sid) {
        //必然存在
        //定义  索引 默认值为-1
        int index = -1;
        //查看学号对应的学生在数组中的位置
        for (int i = 0; i < stus.size(); i++) {
            //stus[i]
            Student stu = stus.get(i);
            if (stu != null && stu.getSid().equals(sid)) {
                index = i;
                break;
            }
        }
        return index;
    }

    public void updateStudent(String sid, Student student) {
        //查看 学号对应的学生的索引
        int index = getIndex(sid);

        //把新的学生替换旧的学生
        stus.set(index,student);

    }
}
